/**
 * 
 */
package org.thattoolkit.srvctl.apache22;

import java.util.Map;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.HierarchicalINIConfiguration;
import org.apache.commons.configuration.SubnodeConfiguration;
import org.apache.commons.configuration.tree.ConfigurationNode;

/**
 * @author ulrb
 *
 */
public class ConfigurationFinder {
	static String configFile;
	static private ConfigurationFinder _instance;
	static private HierarchicalINIConfiguration configurations; 
	
	static synchronized ConfigurationFinder getInstance() throws ConfigurationException, NamingException {
		if(_instance == null) {
			Context initCtx = new InitialContext();
			Context envCtx = (Context) initCtx.lookup("java:comp/env");
			String cf = (String) envCtx.lookup("ConcigurationFinder.configFile");
			_instance = new ConfigurationFinder(cf);
		}
		return _instance;
	}
	
	private ConfigurationFinder(String _file) throws ConfigurationException {
		configFile = _file;
		configurations.load(configFile);
	}
	
	/**
	 * @param ntry
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 */
	ConfigurationNode FindConfigurationEntry(String ntry, boolean isSect) 
			throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		SubnodeConfiguration sc = configurations.getSection(ntry);
		String cls = sc.getString("class", "");
		if(cls.isEmpty())
			throw new ClassNotFoundException(ntry+": Missing class entry");
		ConfigurationNode result = (ConfigurationNode) Class.forName(cls).newInstance();
		result.setName(ntry);
		if(isSect)
			result.setReference(true);
		return result;
	}
}
